<!--
@description    编辑\添加指标规则-弹窗
@author         秦俊强
@email          458112865@qq.com
@create         2020-03-21 10:10
-->

<template>
  <a-modal :title="record ? '编辑规则' : '添加规则'" :width="'80%'" :visible="show"
           @ok="save" @cancel="cancel" cancelText="关闭">
    <div class="form-box">
      <a-form>

        <a-form-item label="指标部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-tree-select :treeDefaultExpandAll="true"
                         :treeData="groupOrgs" :key="'value'"
                         :dropdownStyle="{ 'max-height': '280px', 'overflow': 'auto' }"
                         v-model="param.indexDepart" @change="changeOrg"></a-tree-select>
        </a-form-item>

        <a-form-item label="数据列标识" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select :value="param.whichData.name" @change="changeWhich">
            <a-select-option v-for="opt in whichData" :key="opt.code">
              <span>{{ opt.name }}</span>
              <span v-if="opt.code">[ {{ opt.code }} ]</span>
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="数据项" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select placeholder="搜索数据项" showSearch
                    :value="param.indexValue.name"
                    :filterOption="false"
                    :notFoundContent="indexValue.notFound"
                    :loading="indexValue.loading"
                    @search="searchIndexVals"
                    @select="changeIndexText">
            <a-select-option v-for="opt in indexValue.searchArr" :key="opt.code">
              <span>{{ opt.name }} [ {{ opt.code }} ]</span>
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="变量计算公式" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea placeholder="请输入变量计算公式" v-model="param.indexValueRule" />
        </a-form-item>

        <a-form-item label="中文计算公式" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea placeholder="请输入中文计算公式" v-model="param.indexValueRuleCn" />
        </a-form-item>

        <a-form-item label="指标值规则说明" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea placeholder="请输入指标值规则说明" v-model="param.indexValueRuleComments" />
        </a-form-item>

      </a-form>
    </div>
  </a-modal>
</template>



<script>
  /* 封装通用 api 服务 */
  import { apiService } from '@/api/api.service.js';

  /**
   * api 接口
   *
   * getIndexGroupOrgs => 部门选择项
   * whichDataList => 数据列标识
   * searchIndexValue => 数据项编码
   * */
  import { getIndexGroupOrgs, whichDataList, searchIndexValue } from '@/api/api.js'




  export default {
    name: "TkIndexValueRuleModal",

    props: {
      record: null,
      ok: null
    },

    data () {
      return {
        title: '',
        show: false,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 },
        },

        /* 可选部门 */
        groupOrgs: [],

        /* 数据列标识 */
        whichData: [],

        /* 数据项 模糊搜索 */
        indexValue: {
          resArr: [],     // 源数组
          searchArr: [],  // 搜索数组
          loading: false,
          notFound: null
        },

        /* 保存 | 编辑时的参数 */
        param: {
          indexDepart: '',              // 部门
          whichData: {},                // 数据列标识
          indexValue: {},               // 数据项

          indexValueRule: '',           // 变量公式
          indexValueRuleCn: '',         // 变量公式-中文
          indexValueRuleComments: ''    // 变量公式说明
        },

        /* 延时搜索数据项 */
        timeout: null
      }
    },

    created() {
      this.getIndexGroupOrgs();
      this.whichDataList();
      this.searchIndexValue();

      this.$watch('show', (b) => {
        if (b) {
          this.initRecord();
          this.searchIndexVals();
        }
      });
    },

    methods: {

      /* 初始化参数 */
      initRecord() {
        this.param = {
          indexDepart: '',              // 部门
          whichData: {},                // 数据列标识
          indexValue: {},               // 数据项

          indexValueRule: '',           // 变量公式
          indexValueRuleCn: '',         // 变量公式-中文
          indexValueRuleComments: ''    // 变量公式说明
        }

        if (this.record) {
          this.param.indexDepart = this.record.indexDepart;
          this.changeWhich(this.record.whichData);
          this.changeIndexText(this.record.indexValueCode);

          this.param.indexValueRule = this.record.indexValueRule;
          this.param.indexValueRuleCn = this.record.indexValueRuleCn;
          this.param.indexValueRuleComments = this.record.indexValueRuleComments;

          return;
        }

        let initData = this.groupOrgs[0];
        this.changeOrg(initData.value, [initData.title]);
        this.param.whichData = this.whichData[0];
      },

      /* 监听部门的变化 */
      changeOrg(val) {
        this.param.indexDepart = val;
      },

      /* 监听 数据列标识的变化 */
      changeWhich(code) {
        if (!code) {
          this.param.whichData = this.whichData[0];
          return;
        }
        this.param.whichData = this.whichData.find((item) => { return (item.code === code); });
      },

      /* 监听选中数据项关键字的变化 */
      changeIndexText(code) {
        this.param.indexValue = this.indexValue.searchArr.find((item) => { return (item.code === code); });
      },

      /* 监听数据项关键字的变化 进行模糊搜索 */
      searchIndexVals(value) {
        clearTimeout(this.timeout);   // 清除定时器

        this.timeout = setTimeout(() => {
          if (value && value.trim()) {
            this.indexValue.searchArr = this.indexValue.resArr.filter((item) => {
              return item.code.indexOf(value) >= 0 || item.name.indexOf(value) >= 0;
            });

            if (this.indexValue.searchArr.length === 0) {
              this.indexValue.notFound = '未找到数据项';
            } else {
              this.indexValue.notFound = null;
            }
          } else {
            this.indexValue.searchArr = JSON.parse(JSON.stringify(this.indexValue.resArr));
          }
        }, 500);
      },

      /* 取消编辑 */
      cancel() { this.show = false; },

      /* 保存 */
      save() {
        let param = this.param;

        if (!param.indexValue.code) {
          this.$message.warning('数据项不能为空');
          return;
        }

        this.ok && this.ok({
          "id": this.record.id || '',                   // id 没有表示添加，有表示编辑

          "indexDepart": param.indexDepart,       // 指标部门
          // "indexDepartName": param.indexDepart.text,

          "whichData": param.whichData.code,            // 数据列
          "whichDataName": param.whichData.name,

          "indexValueCode": param.indexValue.code,      // 数据项
          "indexValueName": param.indexValue.name,

          "indexValueRule": param.indexValueRule,       // 变量公式
          "indexValueRuleCn": param.indexValueRuleCn,   // 变量公式-中文
          "indexValueRuleComments": param.indexValueRuleComments,   // 变量公式-说明
        });
      },

      /* 获取可选部门信息 */
      getIndexGroupOrgs() {
        apiService(getIndexGroupOrgs()).then((res) => {
          let resData = res.result;

          for (let i = 0; i < resData.length; i++) {
            let item = resData[i];
            let options = {
              title: item.text,
              value: item.value,
              key: item.value,
              // selectable: false,
              children: []
            }

            for (let j = 1; j < item.orgs.length; j++) {
              let cItem = item.orgs[j];
              options.children.push({ title: cItem.text, value: cItem.value, key: cItem.value });
            }

            this.groupOrgs.push(options);
          }

          this.groupOrgs.unshift({ key: '', title: '全部部门', value: '' });
        }).catch((error) => {
          this.$message.error(error.message);
        });
      },

      /* 数据列标识 */
      whichDataList() {
        apiService(whichDataList()).then((res) => {
          this.whichData = res.result.whichData;
          this.whichData.unshift({ code: '', name: '全部'});
        }).catch((error) => {
          this.$message.error(error.message);
        });
      },

      /* 模糊搜索数据项 */
      searchIndexValue() {
        this.indexValue.loading = true;
        apiService(searchIndexValue({ searchText: '' })).then((res) => {
          this.indexValue.loading = false;
          this.indexValue.resArr = res.result.indexValueCode || [];
          this.indexValue.searchArr = JSON.parse(JSON.stringify(this.indexValue.resArr));
        }).catch((error) => {
          this.indexValue.loading = false;
          this.$message.error(error.message);
        });
      }

    }
  }
</script>



<style lang="less" scoped>
  .form-box {
    padding: 10px 5%;
    textarea { min-height: 80px; }
  }
</style>
